/* eslint-disable */
import React, { useState, useEffect, useCallback } from 'react';
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.min.css';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import moment from 'moment';
import { debounce } from 'lodash';

const TeacherMessages = () => {
    const [messages, setMessages] = useState([]);
    const [reply, setReply] = useState('');
    const [selectedMessageId, setSelectedMessageId] = useState(null);
    const [likes, setLikes] = useState({});
    const [teacherName, setTeacherName] = useState('');
    const [teacherId, setTeacherId] = useState('');
    const [likedMessages, setLikedMessages] = useState(new Set());
    const [unreadCount, setUnreadCount] = useState(0);
    const [filterType, setFilterType] = useState('all'); // 'all', 'unread', 'read'

    const getToken = () => {
        return localStorage.getItem('token');
    };

    useEffect(() => {
        const token = getToken();
        if (!token) {
            console.error('No token found');
            return;
        }

        axios.get('/api/v2/teachers/me', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
            .then(response => {
                setTeacherName(response.data.name);
                setTeacherId(response.data.id);
            })
            .catch(error => {
                console.error('There was an error fetching the teacher info!', error);
            });

        fetchMessages();
    }, []);

    const fetchMessages = () => {
        const token = getToken();
        axios.get('/api/v2/teacher/messages/all', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
            .then(response => {
                const messagesData = response.data.map(message => ({
                    ...message,
                    isRead: message.read,
                    replies: message.replies || [] // 确保 replies 是一个数组
                }));
                setMessages(messagesData);
    
                const initialLikes = messagesData.reduce((acc, message) => {
                    acc[message.id] = message.likes || 0;
                    return acc;
                }, {});
                setLikes(initialLikes);
    
                const unreadMessages = messagesData.filter(msg => !msg.read);
                setUnreadCount(unreadMessages.length);
    
                const initialLikedMessages = new Set(
                    messagesData
                        .filter(message => message.likedByCurrentTeacher)
                        .map(message => message.id)
                );
                setLikedMessages(initialLikedMessages);
            })
            .catch(error => {
                console.error('There was an error fetching the messages!', error);
            });
    };

    const handleReplyChange = (value) => {
        setReply(value);
    };

    const handleReplySubmit = useCallback(debounce((messageId) => {
        if (!reply.trim()) {
            toast.error('发送内容不能为空');
            return;
        }

        const token = getToken();
        if (!token) {
            console.error('No token found');
            return;
        }

        const plainTextReply = reply.replace(/<[^>]+>/g, '');

        axios.post(`/api/v2/teacher/messages/${messageId}/reply`, {
            content: plainTextReply,
            teacherName: teacherName,
            teacherId: teacherId
        }, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
            .then(response => {
                toast.success('回复成功！');
                setReply('');
                setSelectedMessageId(null);

                // 更新消息列表，将回复的消息标记为已读
                setMessages(prevMessages =>
                    prevMessages.map(message =>
                        message.id === messageId
                            ? {
                                ...message,
                                replies: [...message.replies, response.data],
                                isRead: true
                            }
                            : message
                    )
                );

                // 更新未读消息数
                setUnreadCount(prev => Math.max(0, prev - 1));
            })
            .catch(error => {
                console.error('回复发送失败！', error);
                toast.error('回复发送失败，请稍后重试');
            });
    }, 300), [reply, teacherName, teacherId]);

    const handleLike = (messageId) => {
        if (likedMessages.has(messageId)) {
            toast.error('您已经点赞过这条留言');
            return;
        }

        const token = getToken();
        if (!token) {
            console.error('No token found');
            return;
        }

        axios.post(`/api/v2/teacher/messages/${messageId}/like`, {}, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
            .then(() => {
                setLikes(prevLikes => ({
                    ...prevLikes,
                    [messageId]: (prevLikes[messageId] || 0) + 1
                }));
                setLikedMessages(prev => new Set([...prev, messageId]));
                toast.success('点赞成功！');
            })
            .catch(error => {
                console.error('点赞失败！', error);
                toast.error('点赞失败，请稍后重试');
            });
    };

    const handleDeleteReply = (messageId, replyId) => {
        console.log('Current teacherId:', teacherId);
        console.log('Reply teacherId:', reply.teacherId);
        const token = getToken();
        if (!token) {
            console.error('No token found');
            return;
        }

        axios.delete(`/api/v2/teacher/messages/${messageId}/replies/${replyId}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
            .then(() => {
                toast.success('回复删除成功！');
                // 更新消息列表
                setMessages(prevMessages =>
                    prevMessages.map(message =>
                        message.id === messageId
                            ? {
                                ...message,
                                replies: message.replies.filter(reply => reply.id !== replyId)
                            }
                            : message
                    )
                );
            })
            .catch(error => {
                if (error.response && error.response.status === 403) {
                    toast.error('您只能删除自己发布的回复');
                } else if (error.response && error.response.status === 400) {
                    toast.error('只能删除2分钟内发布的回复');
                } else {
                    console.error('删除回复失败！', error);
                    toast.error('删除失败，请稍后重试');
                }
            });
    };

    const handleDeleteMessage = (messageId) => {
        const token = getToken();
        if (!token) {
            console.error('No token found');
            return;
        }

        axios.delete(`/api/v2/teacher/messages/${messageId}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
            .then(() => {
                toast.success('留言删除成功！');
                // 更新消息列表
                setMessages(prevMessages => prevMessages.filter(message => message.id !== messageId));
            })
            .catch(error => {
                console.error('删除留言失败！', error);
                toast.error('删除失败，请稍后重试');
            });
    };

    const getFilteredMessages = () => {
        switch (filterType) {
            case 'unread':
                return messages.filter(msg => !msg.isRead);
            case 'read':
                return messages.filter(msg => msg.isRead);
            default:
                return messages;
        }
    };

    const canDeleteReply = (reply) => {
        const currentTime = moment();
        const replyTime = moment(reply.createdAt);
        return reply.teacherId === teacherId &&
            currentTime.diff(replyTime, 'minutes') <= 2;
    };

    return (
        <div className="container mt-4">
            <ToastContainer />

            <div className="mb-4" style={{ marginTop: '-20px' }}>
                <div className="btn-group">
                    <button
                        className={`btn ${filterType === 'all' ? 'btn-primary' : 'btn-outline-primary'}`}
                        onClick={() => setFilterType('all')}
                    >
                        全部留言
                    </button>
                    <button
                        className={`btn ${filterType === 'unread' ? 'btn-primary' : 'btn-outline-primary'}`}
                        onClick={() => setFilterType('unread')}
                    >
                        未读留言 ({unreadCount})
                    </button>
                    <button
                        className={`btn ${filterType === 'read' ? 'btn-primary' : 'btn-outline-primary'}`}
                        onClick={() => setFilterType('read')}
                    >
                        已读留言
                    </button>
                </div>
            </div>

            <div className="list-group">
                {getFilteredMessages().map(message => (
                    <div key={message.id} className="list-group-item">
                        <div className="d-flex justify-content-between align-items-center">
                            <div className="flex-grow-1">
                                <p className="mb-1">{message.content}</p>
                                <small className="text-muted">
                                    {moment(message.createdAt).format('YYYY-MM-DD HH:mm:ss')}
                                </small>
                                {!message.isRead &&
                                    <span className="badge bg-danger ms-2">未读</span>
                                }
                            </div>
                            <div className="d-flex align-items-center">
                                <button
                                    className={`btn ${likedMessages.has(message.id) ? 'btn-primary' : 'btn-outline-primary'} btn-sm`}
                                    onClick={() => handleLike(message.id)}
                                    disabled={likedMessages.has(message.id)}
                                >
                                    👍 {likes[message.id] || 0}
                                </button>
                                <button
                                    className="btn btn-outline-primary btn-sm"
                                    onClick={() => setSelectedMessageId(selectedMessageId === message.id ? null : message.id)}
                                >
                                    回复
                                </button>
                                <button
                                    className="btn btn-outline-danger btn-sm"
                                    onClick={() => handleDeleteMessage(message.id)}
                                >
                                    删除留言
                                </button>
                            </div>
                        </div>

                        {message.replies && message.replies.length > 0 && (
                            <div className="mt-3">
                                {message.replies.map(reply => (
                                    console.log('Reply object:', reply),
                                    <div key={reply.id} className="border-start border-3 ps-3 mb-2">
                                        <div className="d-flex justify-content-between">
                                            <div>
                                                <strong>{reply.teacherName}: </strong>
                                                {reply.content}
                                                <br />
                                                <small className="text-muted">
                                                    {moment(reply.createdAt).format('YYYY-MM-DD HH:mm:ss')}
                                                </small>
                                            </div>
                                            {canDeleteReply(reply) && (
                                                <button
                                                    className="btn btn-outline-danger btn-sm"
                                                    onClick={() => handleDeleteReply(message.id, reply.id)}
                                                >
                                                    删除
                                                </button>
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}

                        {selectedMessageId === message.id && (
                            <div className="mt-3">
                                <ReactQuill
                                    value={reply}
                                    onChange={handleReplyChange}
                                    placeholder="请输入回复内容..."
                                />
                                <button
                                    className="btn btn-primary btn-sm mt-2"
                                    onClick={() => handleReplySubmit(message.id)}
                                >
                                    发送回复
                                </button>
                            </div>
                        )}
                    </div>
                ))}
            </div>
        </div>
    );
};

export default TeacherMessages;